var options={
    enableKeyWarp:true,           //jsonkey  引号包裹
    enableFold:true,                //代码折叠是否开启  
    enableKeyBind:true,         //键盘事件
    autoJsonParse:true,         //自动json解析
    autoBaiduBind:true,         //自动百度页面键盘事件添加
    keyMapAlias:{},                 //keymap别名
};
var event={
    init:(d,c)=>{
        if (localStorage.gce_options)  {
            opt = JSON.parse(localStorage.gce_options);
            for(let n in opt) options[n]=opt[n];
        }
        //传递配置信息
        c(event.create('changeOptions',options));
        //调用页面init
        return options;
    },
    //加载文件 json.js
    loadJson:(jsonStr,callback)=>{
                    chrome.tabs.executeScript(null, {file: "lib/json.js"},function(){
                                //加载keymap
                                if(options.enableKeyBind && options.enableKeyBind){
                                        chrome.tabs.executeScript(null,{file:"lib/keycode_alias.js"},function(){
                                                chrome.tabs.executeScript(null,{file:"lib/json_keymap.js"})
                                        })
                                }
                                chrome.tabs.executeScript(null,{code:"console.log('load json.js ok')"})
                                callback("load ok");
                    });
//                        json = new Worker("json.js");
//                        let html=json.format(jsonStr)
                        return false;
    },
    loadKeyBind:()=>{
                    chrome.tabs.executeScript(null, {file: "lib/keycode_alias.js"},function(){
                                chrome.tabs.executeScript(null,{file:"lib/keydown.js"})
                                callback("load ok");
                    });
    },
    create:(type,data,name)=>{
            return (!data.event) ? {
                event :type,
                name:name,
                data:data
            }: data;
    }
};

function upOptions(opt){
    console.log(opt);   
}

function init() {
    chrome.runtime.onConnect.addListener(function (port) {
               port.onMessage.addListener(function(msg) {
                    if(msg.event){
                        let name =msg.event;
                        //name=name.charAt(0).toUpperCase() + name.slice(1);
                        let func=event[name];
                        let rt=func ? func(msg.data,function(params){
                            let ev=event.create('success',params,name)
                            port.postMessage(ev);
                        }): msg;
                        if(rt)    return port.postMessage(event.create(name,rt));
                    }
               });
    });
}
init();